#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys
import json
import cgi
import datetime
import db_conf
con = None
try:
    qform = cgi.FieldStorage()
    compound_id = qform.getvalue('compound_id')
    config = db_conf.getConfig('metabvis.conf')
    con = psycopg2.connect(host=db_conf.getDBHost(config), database=db_conf.getDBName(config), port=db_conf.getDBPort(config), user=db_conf.getUser(config), password=db_conf.getPassword(config))
    cur = con.cursor()
    sel_compound = 'select c.compound_name, de.reagent_name, cd.precursor_compound from compound c, compound_derivatization cd, derivatization_reagent de where c.compound_id = cd.precursor_compound and cd.derivatization_reagent_id = de.reagent_id and cd.product_compound =' + compound_id
    cur.execute(sel_compound)          
    rows = cur.fetchall()
    print "Content-type: text/html;charset=utf-8\r\n"
    pa = {}
    pa['precursorCompoundData'] = []
    for row in rows:
        pi = []
        ct = 0
        for r in range(len(row)):
            ct = ct + 1
            #if (ct < 2):
            pi.append(str(row[r]))
        #pop last element from array
        pi.pop()
        pi.append("<a href=javascript:show_precursor_details('" + str(row[2]) + "')>Details</a>")
        pi.append("<a href=javascript:delete_precursor_compound('" + str(row[2]) + "')>Delete</a>")
        pa['precursorCompoundData'].append(pi)
    print json.dumps(pa)
except psycopg2.DatabaseError, e:
    print 'Error %s' % e    
    sys.exit(1)    
finally:
    if con:
        con.close()
